package com.lkd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyChannel;
import com.lkd.contract.SupplyContract;
import com.lkd.contract.TaskCompleteContract;
import com.lkd.dao.TaskDao;
import com.lkd.emq.MqttProducer;
import com.lkd.entity.TaskDetailsEntity;
import com.lkd.entity.TaskEntity;
import com.lkd.entity.TaskStatusTypeEntity;
import com.lkd.entity.UserEntity;
import com.lkd.exception.LogicException;
import com.lkd.feign.UserService;
import com.lkd.feign.VMService;
import com.lkd.http.vo.CancelTaskViewModel;
import com.lkd.http.vo.TaskReportInfoVO;
import com.lkd.http.vo.TaskStatusVo;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskDetailsService;
import com.lkd.service.TaskService;
import com.lkd.service.TaskStatusTypeService;
import com.lkd.vo.Pager;
import com.lkd.vo.UserVO;
import com.lkd.vo.UserWorkVO;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@Slf4j
public class TaskServiceImpl extends ServiceImpl<TaskDao, TaskEntity> implements TaskService {

    @Autowired
    private TaskStatusTypeService statusTypeService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private VMService vmService;

    @Autowired
    private UserService userService;

    @Autowired
    private TaskDetailsService taskDetailsService;

    @Autowired
    MqttProducer mqttProducer;

    @Autowired
    private TaskService taskService;


    @Override
    public Pager<TaskEntity> search(Long pageIndex, Long pageSize, String innerCode, Integer userId, String taskCode, Integer status, Boolean isRepair, String start, String end) {
        Page<TaskEntity> page = new Page<>(pageIndex, pageSize);
        LambdaQueryWrapper<TaskEntity> qw = new LambdaQueryWrapper<>();
        if (!Strings.isNullOrEmpty(innerCode)) {
            qw.eq(TaskEntity::getInnerCode, innerCode);
        }
        if (userId != null && userId > 0) {
            qw.eq(TaskEntity::getUserId, userId);
        }
        if (!Strings.isNullOrEmpty(taskCode)) {
            qw.like(TaskEntity::getTaskCode, taskCode);
        }
        if (status != null && status > 0) {
            qw.eq(TaskEntity::getTaskStatus, status);
        }
        if (isRepair != null) {
            if (isRepair) {
                qw.ne(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
            } else {
                qw.eq(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
            }
        }
        if (!Strings.isNullOrEmpty(start) && !Strings.isNullOrEmpty(end)) {
            qw
                    .ge(TaskEntity::getCreateTime, LocalDate.parse(start, DateTimeFormatter.ISO_LOCAL_DATE))
                    .le(TaskEntity::getCreateTime, LocalDate.parse(end, DateTimeFormatter.ISO_LOCAL_DATE));
        }
        //根据最后更新时间倒序排序
        qw.orderByDesc(TaskEntity::getUpdateTime);

        return Pager.build(this.page(page, qw));
    }


    @Override
    public List<TaskStatusTypeEntity> getAllStatus() {
        QueryWrapper<TaskStatusTypeEntity> qw = new QueryWrapper<>();
        qw.lambda()
                .ge(TaskStatusTypeEntity::getStatusId, VMSystem.TASK_STATUS_CREATE);

        return statusTypeService.list(qw);
    }


    @Transactional
    @Override
    public boolean createTask(TaskViewModel taskViewModel) throws LogicException {
        //跨服务查询售货机微服务，得到售货机的地址和区域id
        VmVO vm = vmService.getVMInfo(taskViewModel.getInnerCode());
        if (vm == null) {
            throw new LogicException("该机器不存在");
        }
        //跨服务查询用户微服务，得到用户名
        UserVO user = userService.getUser(taskViewModel.getUserId());
        if (user == null) {
            throw new LogicException("该用户不存在");
        }
        checkCreateTask(vm.getVmStatus(), taskViewModel.getProductType());//验证售货机状态
        //我们在创建工单时应该校验这台设备是否有未完成的同类型工单，如果存在则不能创建
        if (hasTask(taskViewModel.getInnerCode(), taskViewModel.getProductType())) {
            throw new LogicException("该机器有未完成的同类型工单");
        }
        //新增工单表记录
        TaskEntity taskEntity = new TaskEntity();
        taskEntity.setTaskCode(generateTaskCode());//工单编号
        BeanUtils.copyProperties(taskViewModel, taskEntity);//复制属性
        taskEntity.setTaskStatus(VMSystem.TASK_STATUS_CREATE);//工单状态
        taskEntity.setProductTypeId(taskViewModel.getProductType());//工单类型

        taskEntity.setAddr(vm.getNodeAddr());//地址
        taskEntity.setRegionId(vm.getRegionId());//区域
        taskEntity.setUserName(user.getUserName());//用户名
        this.save(taskEntity);
        //如果是补货工单，向 工单明细表插入记录
        if (taskEntity.getProductTypeId() == VMSystem.TASK_TYPE_SUPPLY) {
            taskViewModel.getDetails().forEach(d -> {
                TaskDetailsEntity detailsEntity = new TaskDetailsEntity();
                BeanUtils.copyProperties(d, detailsEntity);
                detailsEntity.setTaskId(taskEntity.getTaskId());
                taskDetailsService.save(detailsEntity);
            });
        }
        increadTaskZset(taskEntity, 1);//该方法是用于： 如果创建工单，就向工单列表中加1
        return true;
    }

    /**
     * 如果创建工单，就向工单列表中score自增一定数值
     *
     * @param taskEntity
     * @param score
     */
    private void increadTaskZset(TaskEntity taskEntity, int score) {
        String roleCode = "1003"; //运维员
        if (taskEntity.getProductTypeId() == VMSystem.TASK_TYPE_SUPPLY) { //如果是补货工单
            roleCode = "1002"; //更改为运营人员
        }
        //设置存储到redis中的ZSet集合中的key值
        String key = VMSystem.REGION_TASK_KEY_PREF   //固定字符串（区域工单统计前缀）
                + "." + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))  //当前时间并格式化
                + "." + taskEntity.getRegionId()  //当前用户的区域id
                + "." + roleCode;//当前用户的角色id
        //构建数据（zset）
        redisTemplate.opsForZSet().incrementScore(key, taskEntity.getUserId(), score); //incrementScore： 用于自增score ，自增数目为score
    }

    @Override
    public int getLeastUser(Long regionId, Boolean isRepair) {
        String roleCode = "1003";
        if (!isRepair) {
            roleCode = "1002";
        }
        String key = VMSystem.REGION_TASK_KEY_PREF   //固定字符串（区域工单统计前缀）
                + "." + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))  //当前时间并格式化
                + "." + regionId //当前用户的区域id
                + "." + roleCode;//当前用户的角色id
        //根据keey查询第一条数据的Value
        Set<Object> rangeUser = redisTemplate.opsForZSet().range(key, 0, 0);//查询第一条数据
        if (rangeUser == null || rangeUser.isEmpty()) {
            return 0; //如果没有数据返回0
        }
        return (Integer) rangeUser.stream().collect(Collectors.toList()).get(0); //Collectors.toList()将set转成list集合
    }


    /**
     * 创建工单校验
     *
     * @param vmStatus
     * @param productType
     * @throws LogicException
     */
    private void checkCreateTask(Integer vmStatus, int productType) {
        //如果是投放工单，状态为运营
        if (productType == VMSystem.TASK_TYPE_DEPLOY && vmStatus == VMSystem.VM_STATUS_RUNNING) {
            throw new LogicException("该设备已在运营状态");
        }
        //如果是补货工单，状态不是运营状态
        if (productType == VMSystem.TASK_TYPE_SUPPLY && vmStatus != VMSystem.VM_STATUS_RUNNING) {
            throw new LogicException("该设备不在运营状态");
        }
        //如果是撤机工单，状态不是运营状态
        if (productType == VMSystem.TASK_TYPE_REVOKE && vmStatus != VMSystem.VM_STATUS_RUNNING) {
            throw new LogicException("该设备不在运营状态");
        }

    }

    /**
     * 同一台设备下是否存在未完成的工单
     *
     * @param innerCode
     * @param productionType
     * @return
     */
    private boolean hasTask(String innerCode, int productionType) {
        QueryWrapper<TaskEntity> qw = new QueryWrapper<>();
        qw.lambda()
                .select(TaskEntity::getTaskId)
                .eq(TaskEntity::getInnerCode, innerCode)
                .eq(TaskEntity::getProductTypeId, productionType)
                .le(TaskEntity::getTaskStatus, VMSystem.TASK_STATUS_PROGRESS);
        return this.count(qw) > 0;
    }


    /**
     * 生成工单编号
     *
     * @return
     */
    private String generateTaskCode() {
        //日期+序号
        String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));  //日期字符串
        String key = "lkd.task.code." + date; //redis key
        Object obj = redisTemplate.opsForValue().get(key);
        if (obj == null) {
            redisTemplate.opsForValue().set(key, 1L, Duration.ofDays(1));
            return date + "0001";
        }
        return date + Strings.padStart(redisTemplate.opsForValue().increment(key, 1).toString(), 4, '0');
    }


    @Override
    public boolean accept(Long id) {
        TaskEntity task = this.getById(id);  //查询工单
        if (task.getTaskStatus() != VMSystem.TASK_STATUS_CREATE) {
            throw new LogicException("工单状态不是待处理");
        }
        task.setTaskStatus(VMSystem.TASK_STATUS_PROGRESS);//修改工单状态为进行
        return this.updateById(task);
    }

    @Override
    public boolean cancelTask(Long id, CancelTaskViewModel cancelVM) {
        TaskEntity task = this.getById(id);  //查询工单
        if (task.getTaskStatus() == VMSystem.TASK_STATUS_CANCEL || task.getTaskStatus() == VMSystem.TASK_STATUS_FINISH) {
            throw new LogicException("工单已经结束");
        }
        task.setTaskStatus(VMSystem.TASK_STATUS_CANCEL);
        task.setDesc(cancelVM.getDesc());
        increadTaskZset(task, -1);//该方法是用于： 如果创建工单，就向工单列表中加-1
        return this.updateById(task);
    }

    @Override
    public boolean completeTask(long id) {
        TaskEntity taskEntity = this.getById(id);
        if (taskEntity.getTaskStatus() == VMSystem.TASK_STATUS_CANCEL || taskEntity.getTaskStatus() == VMSystem.TASK_STATUS_FINISH) {
            throw new LogicException("工单已经结束");
        }
        taskEntity.setTaskStatus(VMSystem.TASK_STATUS_FINISH);//修改工单状态
        this.updateById(taskEntity);
        //如果是投放工单或者撤机工单
        if (taskEntity.getProductTypeId() == VMSystem.TASK_TYPE_DEPLOY || taskEntity.getProductTypeId() == VMSystem.TASK_TYPE_REVOKE) {
            noticeVMServiceStaus(taskEntity);//运维工单协议的封装与下发
        }
        //如果是补货工单
        if (taskEntity.getProductTypeId() == VMSystem.TASK_TYPE_SUPPLY) {
            noticeVMServiceSupply(taskEntity);//补货协议的封装与下发
        }
        return true;
    }


    /**
     * 运维工单协议的封装与下发
     *
     * @param taskEntity
     */
    private void noticeVMServiceStaus(TaskEntity taskEntity) {
        //向消息队列发送消息，通知售货机更改状态
        //封装协议
        TaskCompleteContract taskCompleteContract = new TaskCompleteContract();
        taskCompleteContract.setInnerCode(taskEntity.getInnerCode());
        taskCompleteContract.setTaskType(taskEntity.getProductTypeId());
        try {
            mqttProducer.send(TopicConfig.VMS_COMPLETED_TOPIC, 2, taskCompleteContract);
        } catch (JsonProcessingException e) {
            log.error("发送工单完成协议出错");
            throw new LogicException("发送工单完成协议出错");
        }
    }

    /**
     * 补货协议的封装与下发
     *
     * @param taskEntity
     */
    private void noticeVMServiceSupply(TaskEntity taskEntity) {
        //协议内容封装
        //1.根据工单id查询工单明细表
        QueryWrapper<TaskDetailsEntity> qw = new QueryWrapper<>();
        qw.lambda()
                .eq(TaskDetailsEntity::getTaskId, taskEntity.getTaskId());
        List<TaskDetailsEntity> datalis = taskDetailsService.list(qw);
        //2.构建协议内容
        SupplyContract supplyContract = new SupplyContract();
        supplyContract.setInnerCode(taskEntity.getInnerCode());//售货机编号

        ArrayList<SupplyChannel> supplyChannels = Lists.newArrayList(); //补货数据

        datalis.forEach(d -> {
            SupplyChannel supplyChannel = new SupplyChannel();
            supplyChannel.setChannelId(d.getChannelCode()); //货道编号
            supplyChannel.setCapacity(d.getExpectCapacity()); //补货数量
            supplyChannels.add(supplyChannel);
        });

        supplyContract.setSupplyData(supplyChannels);
        //3.下发补货协议
        //发送到emq
        try {
            mqttProducer.send(TopicConfig.VMS_SUPPLY_TOPIC, 2, supplyContract);
        } catch (JsonProcessingException e) {
            log.error("发送工单完成协议出错");
            throw new LogicException("发送工单完成协议出错");
        }

    }

    @Override
    public List<TaskReportInfoVO> collectionUserTask(LocalDateTime start, LocalDateTime end) {

        //运营工单总数
        int operateCount = this.getCount(start, end, false, null);
        //运维工单总数
        int repairerCount = this.getCount(start, end, true, null);
        //完成运营工单总数
        int operateCompleteCount = this.getCount(start, end, false, VMSystem.TASK_STATUS_FINISH);
        //运维工单总数
        int repairerCompleteCount = this.getCount(start, end, true, VMSystem.TASK_STATUS_FINISH);
        //进行运营工单总数
        int operateIngCount = this.getCount(start, end, false, VMSystem.TASK_STATUS_PROGRESS);
        //进行工单总数
        int repairerIngCount = this.getCount(start, end, true, VMSystem.TASK_STATUS_PROGRESS);
        //拒绝运营工单总数
        int operateRefuseCount = this.getCount(start, end, false, VMSystem.TASK_STATUS_CANCEL);
        //拒绝运维工单总数
        int repairerRefuseCount = this.getCount(start, end, true, VMSystem.TASK_STATUS_CANCEL);
        //运营人员总数
        Integer operatorWorkCount = userService.getOperatorCount();
        //运维人员总数
        Integer repairerWorkCount = userService.getRepairerCount();

        List<TaskReportInfoVO> taskCountList = Lists.newArrayList();

        //运营人员的相关信息
        TaskReportInfoVO opreateNews = new TaskReportInfoVO();
        opreateNews.setTotal(operateCount);
        opreateNews.setCompletedTotal(operateCompleteCount);
        opreateNews.setCancelTotal(operateRefuseCount);
        opreateNews.setProgressTotal(operateIngCount);
        opreateNews.setWorkerCount(operatorWorkCount);
        opreateNews.setRepair(false);
        taskCountList.add(opreateNews);

        //运维人员的相关信息
        TaskReportInfoVO repaireNews = new TaskReportInfoVO();
        repaireNews.setTotal(repairerCount);
        repaireNews.setCompletedTotal(repairerCompleteCount);
        repaireNews.setCancelTotal(repairerRefuseCount);
        repaireNews.setProgressTotal(repairerIngCount);
        repaireNews.setWorkerCount(repairerCount);
        repaireNews.setRepair(true);
        taskCountList.add(repaireNews);

        return taskCountList;
    }

    private int getCount(LocalDateTime start, LocalDateTime end, boolean isRepair, Integer taskStatus) {
        LambdaQueryWrapper<TaskEntity> tw = new LambdaQueryWrapper<>(); //创建查询条件
        tw.between(TaskEntity::getUpdateTime, start, end);  //订单更新时间大于开始时间
        //按工单状态查询
        if (taskStatus != null) {
            tw.eq(TaskEntity::getTaskStatus, taskStatus);
        }
        //如果是运维工单
        if (isRepair) {
            tw.ne(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
        } else {//如果是运营工单
            tw.eq(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
        }
        return this.count(tw);
    }

    @Override
    public List<TaskStatusVo> getTaskStaus(LocalDate start, LocalDate end) {
        List<TaskStatusVo> taskStatusVoList = Lists.newArrayList(); //创建一个TaskStatusVo集合
        while (!start.isAfter(end)){
            //完成工单总数
            int finishCount = this.getStatusCount(start, end, VMSystem.TASK_STATUS_FINISH);
            //进行中工单数
            int ingCount = this.getStatusCount(start, end, VMSystem.TASK_STATUS_PROGRESS);
            //取消工单数
            int refuseCount = this.getStatusCount(start, end, VMSystem.TASK_STATUS_CANCEL);

            TaskStatusVo taskStatusVo = new TaskStatusVo(); //创建TaskStatusVo实体对象
            taskStatusVo.setFinishCount(finishCount); //添加完成工单数
            taskStatusVo.setProgressCount(ingCount);  //添加进行中工单数
            taskStatusVo.setCancelCount(refuseCount); //添加取消工单数
            taskStatusVo.setCollectDate(start);
            taskStatusVoList.add(taskStatusVo);  //将添加的实体对象放入taskStatusVoList集合

            start=start.plusDays(1);
        }
        return taskStatusVoList; //返回taskStatusVoList集合
    }

    private int getStatusCount(LocalDate start, LocalDate end, Integer taskStatus) {
        QueryWrapper<TaskEntity> tw = new QueryWrapper<>();
        tw.lambda().between(TaskEntity::getCreateTime, start, end.plusDays(1))
                .eq(TaskEntity::getTaskStatus, taskStatus);
        return this.count(tw);
    }

    @Override
    public UserWorkVO userWorkCount(Integer userId, LocalDateTime start, LocalDateTime end) {

        //所有工单总数
        int totalCount = this.getUserTaskCount(userId, null, start, end);
        //拒绝工单数
        int refuseCount = this.getUserTaskCount(userId, VMSystem.TASK_STATUS_CANCEL, start, end);
        //完成工单总数
        int finishCount = this.getUserTaskCount(userId, VMSystem.TASK_STATUS_FINISH, start, end);
        //进行中工单数
        int ingCount = this.getUserTaskCount(userId, VMSystem.TASK_STATUS_PROGRESS, start, end);
        UserWorkVO userWorkVO = new UserWorkVO();
        userWorkVO.setUserId(userId);
        userWorkVO.setWorkCount(finishCount);
        userWorkVO.setProgressTotal(ingCount);
        userWorkVO.setCancelCount(refuseCount);
        userWorkVO.setTotal(totalCount);
        return userWorkVO;
    }

    /**
     * 根据用户id、工单状态、开始时间、截至时间统计工单数
     *
     * @param userId
     * @param taskStatus
     * @param start
     * @param end
     * @return
     */
    private int getUserTaskCount(Integer userId, Integer taskStatus, LocalDateTime start, LocalDateTime end) {
        QueryWrapper<TaskEntity> tw = new QueryWrapper<>();
        tw.lambda()
                .eq(TaskEntity::getUserId, userId)
                .eq(TaskEntity::getTaskStatus, taskStatus)
                .between(TaskEntity::getUpdateTime, start, end);
        return this.count(tw);
    }

    @Override
    public List<UserWorkVO> userOrder(LocalDate start, LocalDate end, boolean isRepair, Long regionId) {
        QueryWrapper<TaskEntity> tw = new QueryWrapper<>();
        //根据时间，订单状态通过用户名进行分组，通过用户Id进行倒叙查询前十的用户名和订单总数

        tw.select("count(user_id) as user_id,user_name ")
                .lambda()
                .between(TaskEntity::getUpdateTime, start, end.plusDays(1))
                .eq(TaskEntity::getTaskStatus, VMSystem.TASK_STATUS_FINISH)
                .groupBy(TaskEntity::getUserName)
                .orderByDesc(TaskEntity::getUserId)
                .last("limit 10");
        if (regionId > 0) {
            tw.lambda().eq(TaskEntity::getRegionId, regionId); //查询不同区域人的信息
        }
        if (isRepair) {
            tw.lambda().eq(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);//查询运维人员的信息
        } else {
            tw.lambda().eq(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);//查询运营人员的信息
        }

        List<UserWorkVO> userWorkVOS = this.list(tw).stream()
                .map(workerNews -> { //遍历UserWorkVO并添加相关数据
                    UserWorkVO userWorkVO = new UserWorkVO();
                    userWorkVO.setUserName(workerNews.getUserName());
                    userWorkVO.setWorkCount(workerNews.getUserId());
                    return userWorkVO;
                }).collect(Collectors.toList());

        return userWorkVOS;
    }

    private void extracted(Boolean isRespire, TaskReportInfoVO infoVO, TaskEntity taskEntity) {
        int completeCount = 0;
        int ingCount = 0;
        int rejectCount = 0;
        if (taskEntity.getTaskStatus() == VMSystem.TASK_STATUS_FINISH) {
            completeCount += 1;
        }
        if (taskEntity.getTaskStatus() == VMSystem.TASK_STATUS_PROGRESS) {
            ingCount += 1;
        }
        if (taskEntity.getTaskStatus() == VMSystem.TASK_STATUS_CANCEL) {
            ingCount += 1;
        }
        if (isRespire) {
            Integer Count = userService.getRepairerCount();
            infoVO.setWorkerCount(Count);
        } else {
            Integer Count = userService.getOperatorCount();
            infoVO.setWorkerCount(Count);
        }
        infoVO.setTotal(completeCount + rejectCount + ingCount);
        infoVO.setCompletedTotal(completeCount);
        infoVO.setCancelTotal(rejectCount);
        infoVO.setProgressTotal(ingCount);
        infoVO.setRepair(isRespire);
    }

}
